package com.lzy.okgo.harmony.rxharmony.schedulers;

import com.lzy.okgo.harmony.rxharmony.plugins.RxHarmonyPlugins;
import io.reactivex.Scheduler;
import ohos.eventhandler.EventRunner;

/**
 * HarmonyOS，线程调度器工厂
 */
public final class HarmonySchedulers {
    /**
     * 主线程调度器
     */
    private static final Scheduler MAIN_THREAD =
            RxHarmonyPlugins.initMainThreadScheduler(() -> MainHolder.DEFAULT);

    /**
     * 单例，保存主线程调度器
     */
    private static final class MainHolder {
        static final Scheduler DEFAULT = new EventHandlerScheduler(new EventHandlerScheduler.WithIdEventHandler(EventRunner.current()));
    }

    /**
     * 工具类，隐藏构造方法，如果被反射，抛出异常
     */
    private HarmonySchedulers() {
        throw new AssertionError("No instances.");
    }

    /**
     * 获取主线程调度器
     */
    public static Scheduler mainThread() {
        return RxHarmonyPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    /**
     * 可以指定EventRunner，类似Android中的Looper轮训器，所以调度器可以绑定在非主线程中
     */
    public static Scheduler from(EventRunner eventRunner) {
        //判空
        if (eventRunner == null) throw new NullPointerException("looper == null");
        //根据配置，创建对应的主线程调度器
        return new EventHandlerScheduler(new EventHandlerScheduler.WithIdEventHandler(eventRunner));
    }
}